<?php
declare(strict_types=1);

namespace App\AdminApi\Controller;

use App\AdminApi\BasicsController;
use App\AdminApi\Modular\Administer\Service\MenuService;
use App\AdminApi\Modular\Administer\Service\UserService;
use App\Application;
use App\Common\Extend\Guard\Auth;
use App\Common\GuardModel\AdminGuard;
use App\Common\Modular\Administer\Serve\RoleServe;
use App\Common\Modular\Data\Serve\RegionServe;
use Core\HyperfUnit\Response;
use Core\Package\Attribute\Describe;
use Core\Package\ElementPlus\FormCreate\Form;
use Core\Package\ElementPlus\FormCreate\FormItem;
use Core\System\AuthUnit;
use Hyperf\HttpServer\Annotation\{Controller, GetMapping, PostMapping};
use Psr\Http\Message\ResponseInterface;
use Zms\Validate\Validate;
use function Hyperf\Support\make;

#[
    Controller(prefix: "/admin-api/common", server: self::SERVER),
    Auth(guard: self::GUARD, sign: "skip", app: self::APP)
]
class CommonController extends BasicsController
{
    #[
        GetMapping('serlist'),
        Auth(label: ['获取服务列表'], logger: false)
    ]
    public function Serlist(): ResponseInterface
    {
        $server = [];
        foreach (Application::APP as $item) {
            $server[] = [
                'label' => $item['DESC'], 'name' => $item['NAME']
            ];
        }
        return Response::Api()->success(data: $server);
    }

    #[
        GetMapping('permissions-form-data'),
        Auth(label: ['权限树数据'], logger: false)
    ]
    public function permissionsFormData(): ResponseInterface
    {
        $data = AuthUnit::permissionsFormData('admin');
        return Response::Api()->success(data: $data);
    }

    #[
        GetMapping('region-tree'),
        Auth(label: ['地区数据树'], logger: false)
    ]
    public function RegionTree(): ResponseInterface
    {
        return Response::Api()->success(data: container(RegionServe::class)->getTreeFormData());
    }


    #[
        GetMapping('administer-role'),
        Auth(label: ['管理员角色'], logger: false)
    ]
    public function AdministerRole(): ResponseInterface
    {
        return Response::Api()->success(data: container(RoleServe::class)->allRole());
    }

    #[
        GetMapping('msg'),
        Describe("获取消息数量")
    ]
    public function msg(): ResponseInterface
    {
        //游客,返回错误信息
        if ($this->guard()->tourist()) {
            return Response::Api()->success(data: []);
        }
        //律师审核
        $result = [];
        for ($i = 1; $i <= 7; $i++) {
            $result[] = [
                'title' => "测试数据{$i}",
                'name' => "测试{$i}",
                'view' => '/lawyer/auth/index',
                'query' => ['status' => 0],
                'num' => 0
            ];
        }
        return Response::Api()->success(data: $result);
    }


    #[
        GetMapping('news-data'),
        Describe("获取消息数量")
    ]
    public function NewsData(): ResponseInterface
    {
        return Response::Api()->success(data: [

        ]);
    }


    #[
        GetMapping('login-refresh'),
        Auth(label: ['登录刷新'], sign: "skip", logger: false)
    ]
    public function LoginRefresh(): ResponseInterface
    {
        if ($this->guard()->tourist()) {
            return Response::Api()->fail('请先登录');
        }
        $user = $this->user();
        $userData = $user->userInfo();
        return Response::Api()->success(data: [
            'menu' => container(MenuService::class)->getAdministerMenu($user),
            'user' => $userData
        ]);
    }

    #[
        PostMapping('edit-passwd'),
        Auth(label: ['修改登录密码'], logger: 'POST', record: ['account']),
        \Zms\HyperfValidateAnnotations\Validate(
            rules: [
                [['old_password', 'password', 'password2'], 'required'],
                ['password', 'compare', 'find' => 'password2']
            ],
            labels: [
                'old_password' => '旧密码',
                'password' => '新密码',
                'password2' => '确认密码'
            ]
        )
    ]
    public function EditPasswd(): ResponseInterface
    {
        $old_password = $this->request->input('old_password');
        $password = $this->request->input('password');

        /**
         * 验证密码安全性
         */
        $error = container(UserService::class)->checkPassword($password);
        if ($error !== true) {
            return Response::Api()->fail($error);
        }

        /**
         * @var AdminGuard $admin
         */
        $admin = AdminGuard::where(['id' => $this->user()->getId()])->first();
        if ($admin->verifyPassword($old_password, $admin->password, $admin->secret_key) === false) {
            return Response::Api()->fail('旧密码错误');
        }
        $admin->secret_key = $admin->generateSecretKey();
        $admin->password = $admin->generatePassword($password, $admin->secret_key);
        if ($admin->save()) {
            return Response::Api()->success('密码修改成功,请重新登录');
        }
        return Response::Api()->fail('密码修改失败');
    }

    #[
        PostMapping('edit-data'),
        Auth(label: ['修改账号资料'], logger: 'POST', record: ['account'])
    ]
    public function EditData(): ResponseInterface
    {
        $user = $this->user();
        if ($this->request->isMethod('GET')) {
            $rule[] = FormItem::Input('nickname', '管理员昵称', $user->nickname)->clearable(true)->maxlength(20)->required('请输入管理员昵称');
            $rule[] = FormItem::Input('account', '登录账号', $user->account)->placeholder('后台登录账号')->clearable(true)->required('请输入后台登录账号')->maxlength(30);
            $rule[] = FormItem::ImageInput('avatar', '账号头像', $user->avatar)->required('请设置账号头像')->clearable(true);
            $form = Form::create('修改账号资料')->setRules($rule)->setOptionFormInline(true);
            return Response::Api()->success(data: $form->toArray());
        }
        $validate = make(Validate::class)
            ->setLabels(['nickname' => '管理员昵称', 'account' => '登录账号', 'avatar' => '账号头像'])
            ->setRules([
                ['nickname', 'required', 'on' => ['created', 'updated']],
                ['nickname', 'string', 'max' => 20, 'on' => ['created', 'updated']],

                ['account', 'required', 'error' => '{label}不能为空', 'on' => ['created']],
                ['account', 'string', 'min' => 5, 'max' => 30, 'on' => ['created', 'updated']],

                ['avatar', 'required', 'on' => ['created', 'updated']],
                ['avatar', 'string', 'on' => ['created', 'updated']],
            ])
            ->setData($this->request->inputs(['nickname', 'account', 'avatar']))->validate();
        if ($validate->isFail()) {
            return Response::Api()->fail($validate->firstError());
        }
        $data = $validate->getSafeData();
        $data['id'] = $user->getId();
        if (container(UserService::class)->updated($data)) {
            return Response::Api()->success('资料修改成功', $data);
        }
        return Response::Api()->fail('资料资料失败');
    }
}
